﻿#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
 * http://troydhanson.github.io/uthash/userguide.html
 * "uthash.h" source from GitHub : https://github.com/troydhanson/uthash
 * 这是一个hash表的开源项目
 */
#include "uthash.h"

struct hashTable { // 建立hash结构
    int key;    // 键
    int val;    // 值
    UT_hash_handle hh;  // 是内部使用的hash处理句柄   /* makes this structure hashable */
};

struct hashTable *hashtable; // 声明hash表

struct hashTable *find(int ikey) {
    struct hashTable *tmp;
    HASH_FIND_INT(hashtable, &ikey, tmp); // hash 查找元素
    return tmp;
}

void insert(int ikey, int ival) {
    struct hashTable *it = find(ikey);
    if (it == NULL) {
        struct hashTable *tmp = malloc(sizeof(struct hashTable));
        tmp->key = ikey, tmp->val = ival;
        HASH_ADD_INT(hashtable, key, tmp);  // hash 插入元素
    } else {
        it->val = ival;
    }
}

void delete(struct hashTable *element) {
    HASH_DEL(hashtable, element);
    free(element);
}

void print() {
    struct hashTable *s;
    for (s = hashtable; s != NULL; s = (struct hashTable *) (s->hh.next)) {
        printf("user id %d: name %d\n", s->key, s->val);
    }
}

int main() {
    int key = 1;

    for (int i = 1; i <= 10; ++i) {
        insert(key,i);
        key++;
    }

    print();
    printf("\n");
    delete(find(1));
    print();
    printf("\n");
    delete(find(2));
    delete(find(3));
    delete(find(5));
    print();
    printf("\n");
    delete(find(8));
    print();
}